package com.zxl.grocery.microservice.crawler.scheduled;

import com.zxl.grocery.microservice.crawler.entity.CrawlerConfig;
import com.zxl.grocery.microservice.crawler.pipeline.BeautifulPipeline;
import com.zxl.grocery.microservice.crawler.processor.WallProcessor;
import com.zxl.grocery.microservice.crawler.service.biz.CrawlerConfigBiz;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.util.List;

/**
 * @Author: Lzx
 * @Description:
 * @Date: Created in 14:50 2018/1/16
 * @Modified By:
 */
@Component
@EnableScheduling
public class BeautifulScheduled {
    @Autowired
    private BeautifulPipeline beautifulPipeline;
    @Autowired
    private CrawlerConfigBiz crawlerConfigBiz;

    /**
     * 3G壁纸站
     */
    ////[秒] [分] [小时] [日] [月] [周] [年]
    @Scheduled(cron = "0 0 0/4 * * ? ")//从0点开始,每4个小时执行一次
    public void wallScheduled() {
        CrawlerConfig crawlerConfig = new CrawlerConfig();
        crawlerConfig.setCode("WallScheduled");
        List<CrawlerConfig> crawlerConfigs = crawlerConfigBiz.selectList(crawlerConfig);

        if (crawlerConfigs.size() > 0 ) {
            for (int i = 0; i < crawlerConfigs.size(); i++) {
                if (crawlerConfigs.get(i).getContent().equals("1")){
                    CrawlerConfig cConfig = new CrawlerConfig();
                    crawlerConfig.setCode("WallScheduledNum");
                    List<CrawlerConfig> crawlerConfigList = crawlerConfigBiz.selectList(cConfig);

                    if (crawlerConfigList.size() > 0) {
                        for (int j = 0; j < crawlerConfigList.size(); j++) {
                            if(StringUtils.isNotEmpty(crawlerConfigList.get(j).getContent())){
                                System.out.println("----开始执行3G壁纸站定时任务");
                                Spider spider= Spider.create(new WallProcessor());
                                int num=Integer.valueOf(crawlerConfigList.get(j).getContent())+1;
                                System.out.println(crawlerConfigList.get(j).getContent());
                                spider.addUrl("http://www.3gbizhi.com/lists-%E5%85%A8%E9%83%A8/"+num+".html");
                                spider.addPipeline(beautifulPipeline);
                                spider.thread(5);
                                spider.setExitWhenComplete(true);
                                spider.start();
                                spider.stop();
                                crawlerConfigList.get(j).setContent(num+"");
                                crawlerConfigBiz.updateSelectiveById(crawlerConfigList.get(j));
                            }
                        }

                    }
                }

            }

        }

    }
}
